package com.itheima.jobs;

import com.itheima.constant.RedisConstant;
import com.itheima.dao.OrderSettingDao;
import com.itheima.pojo.OrderSetting;
import com.itheima.utils.DateUtils;
import com.itheima.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import redis.clients.jedis.JedisPool;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Set;

/**
 * @Author: Sorry
 * @Date: 2019/7/25
 * @Description: 清理
 */
public class ClearRubbish {


	/**
	 * 导入预约dao层
	 */
	@Autowired
	private OrderSettingDao orderSettingDao;

	@Autowired
	JedisPool jedisPool;


	/**
	 * 定时清理垃圾图片
	 */
	public void clearImg(){
	//	两个set取差值
		Set<String> sdiff = jedisPool.getResource().
				sdiff(RedisConstant.SETMEAL_PIC_RESOURCES, RedisConstant.SETMEAL_PIC_DB_RESOURCES);

		if(!CollectionUtils.isEmpty(sdiff)){
			sdiff.forEach(item->{
				System.out.println("delete:"+item);
				//	遍历set，逐条删除七牛云上面的图片
				QiniuUtils.deleteFileFromQiniu(item);
				//	清空redis垃圾信息
				jedisPool.getResource().srem(RedisConstant.SETMEAL_PIC_RESOURCES,item);
			});

		}
	}


	/**
	 * 定时清理预约设置 （未优化版）
	 */
	public void clearlog() throws Exception {
		//1.获取当前的日期
		LocalDate now = LocalDate.now();
		//2.把日期转成字符串
		String today = getDateStr(now);
		//3.调用dao层查询今天之前的日期
		List<OrderSetting> orderSettingList = orderSettingDao.findOrderSettingByDate(today);
		//4.判断集合是否为空
		if (!CollectionUtils.isEmpty(orderSettingList)){
			//5.不为空遍历
			for (OrderSetting orderSetting : orderSettingList) {
				//6.获取日期转化成字符串
				String orderDate = DateUtils.parseDate2String(orderSetting.getOrderDate());
				//7.判断如果今天的日期 != 之前的日期
				if (!today.equals(orderDate)){
					//根据日期删除
					orderSettingDao.deleteByorderDate(orderDate);
					System.out.println("清理垃圾预约信息"+orderDate);

				}else {
					//清理完成 打印输出
					System.out.println("清理完成 请您及时关闭服务器");
				}
			}
		}
	}

	/**
	 * 生成日期字符串
	 * @param now
	 * @return
	 */
	private String getDateStr(LocalDate now) {
		return DateTimeFormatter.ofPattern("yyyy-MM-dd").format(now);
	}

}
